package com.alan.netty.rpc.v1;

import com.alan.netty.rpc.common.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.SynchronousQueue;

/**
 * @author weiBin
 * @date 2018/11/28
 */
@Slf4j
public class RpcClientHandler extends SimpleChannelInboundHandler<RpcResponse> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception {
        String id = response.getId();
        //获取消息队列
        SynchronousQueue<RpcResponse> queue = RpcClient.getSynchronousQueue(id);
        //添加消息
        queue.put(response);
        //移除对应的消息队列
        RpcClient.removeById(id);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("远程连接异常：", cause);
        ctx.close();
    }
}
